package com.spring.demo.spring_boot.config;

import java.util.Properties;

import javax.annotation.PostConstruct;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.jdbc.core.JdbcTemplate;

import com.github.pagehelper.PageHelper;

/**
 * 
 * @author 王辉阳
 * @date 2017年8月2日 下午4:35:23
 * @description druid数据连接池配置
 */
@Configuration
@PropertySources(value = { @PropertySource(value = "classpath:application-dev-db.properties") })
// @MapperScan(basePackages = "com.spring.demo.spring_boot.mapper")
@Import(DruidDataSourceConfig.class)
public class MyBatisConfig {
	private static Logger logger = LogManager.getLogger(MyBatisConfig.class);
	@Autowired
	private DruidDataSourceConfig druidDataSourceConfig;

	@Bean
	public JdbcTemplate jdbcTemplate() {
		return new JdbcTemplate(druidDataSourceConfig.dataSource());
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(druidDataSourceConfig.dataSource());
		// mybatis分页插件的设置
		PageHelper pageHelper = new PageHelper();
		Properties props = new Properties();
		props.setProperty("dialect", "mysql");
		props.setProperty("reasonable", "true");
		props.setProperty("supportMethodsArguments", "true");
		props.setProperty("returnPageInfo", "check");
		// props.setProperty("params", "count=countSql");
		// 分页查询时会count，true时可使用PageInfo类
		props.setProperty("rowBoundsWithCount", "true");
		pageHelper.setProperties(props); // 添加插件
		sqlSessionFactoryBean.setPlugins(new Interceptor[] { pageHelper });
		return sqlSessionFactoryBean.getObject();
	}

	/**
	 * 非必要时不建议使用
	 * 
	 * @return
	 * @throws Exception
	 */
	@Bean
	public SqlSession sqlSession() throws Exception {
		SqlSessionFactory sqlSessionFactory = sqlSessionFactory();
		return sqlSessionFactory.openSession();
	}

	@PostConstruct
	public void postConstruct() {
		logger.info("数据库配置	=	{}", druidDataSourceConfig);
	}
}
